<?php

class DotImageGenerator {
	
	/* 
	 * In order for this to work you must have neato installed
	 * on your web server and allow it to run the executable
	 * from PHP.
	 * 
	 * I'm no security expert, so I have no idea what the implications
	 * of this method are.  Also, I run Windows at home, so WINDOT wasn't an
	 * option for me.  But things may be different for you...
	 * 
	 * If you have any concerns, advice or better solutions then PLEASE e-mail me.
	 */

	var $sDotText;
	var $sNeatoDirectory;
	
	function DotImageGenerator( $sDotText, $sNeatoDirectory = 'c:/progra~1/att/graphviz/bin/' ) {
		$this->sDotText = $sDotText;
		$this->sNeatoDirectory = $sNeatoDirectory;
	}

	function _GetNeatoOutputFormat( $sImageType ) {
		switch ( strtoupper( $sImageType ) ){
			case 'GIF':
				return '-Tgif';
			case 'CMAP':
				return '-Tcmap';
		}	
		return false;
	}

	function _CheckAccessToNeato() {
		$aOutput = array();
		exec( $this->sNeatoDirectory . 'neato -?', $aOutput );
		if ( $aOutput ) {
			return true;
		}
		echo( 'You do not have access to NEATO on your server: Download NEATO from http://www.graphviz.org and enable access on your webserver' );
		return false;
	}

	function _FormatNeatoHostCommand( $sImageType ) {

		$sOutputFormat = $this->_GetNeatoOutputFormat( $sImageType );
		if ( !$sOutputFormat ) {
			echo( 'Invalid NEATO configuration:' . $sImageType );
			return false;
		}

		return $this->sNeatoDirectory . 'neato ' . $sOutputFormat .  ' -Gepsilon=.00001';
	}
	
	function GenerateImage( $sImageType ) {

		if ( !$this->sDotText ) {
			return false;
		}
		
		if ( !$this->_CheckAccessToNeato() ){
			return false;	
		}
		
		$sCommand = $this->_FormatNeatoHostCommand( $sImageType );
		if ( !$sCommand ) {
			return false;
		}

		return HostProcess::PipeStdInToHostCommand( $sCommand, $this->sDotText );
	}
	
	function GenerateImageFile( $sImageType, $sFilename ) {
		return ( FileHandler::WriteFile( $sFilename, $this->GenerateImage( $sImageType ) ) )?$sFilename:false;
	}

	function GenerateImageInSession( $sImageType, $sImageId ) {
		Session::Start();
		Session::SaveObject( 'Images', $sImageId, $this->GenerateImage( $sImageType ) );
		return $sImageId;
	}
}

require_once( 'Classes/HostProcess.php' );
require_once( 'Classes/FileHandler.php' );
require_once( 'Classes/Session.php' );

?>
